package mjrg.game.frame;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

//这个类用来获取文件的路径，自定义背景的时候用到
public class FileChooser {

  public String getPath() {
    JFileChooser file = new MyChooser(".");
    file.setAcceptAllFileFilterUsed(false);
    file.addChoosableFileFilter(new ExcelFileFilter("jpg", "png", "gif"));  //三种格式的图片可以显示
    int result = file.showOpenDialog(null);
    String path = null;
    if (result == JFileChooser.APPROVE_OPTION) {
      path = file.getSelectedFile().getAbsolutePath();
    }
    return path;
  }

  private class ExcelFileFilter extends FileFilter {
    String ext1, ext2, ext3;

    ExcelFileFilter(String ext1, String ext2, String ext3) {
      this.ext1 = ext1;
      this.ext2 = ext2;
      this.ext3 = ext3;
    }

    public boolean accept(File file) {
      if (file.isDirectory()) return true;
      String fileName = file.getName();
      int index = fileName.lastIndexOf('.');
      if (index > 0 && index < fileName.length() - 1) {         //提取文件后缀
        String extension = fileName.substring(index + 1).toLowerCase();
        if (extension.equals(ext1) || extension.equals(ext2) || extension.equals(ext3))
          return true;
      }
      return false;
    }

    public String getDescription() {
      return "";
    }
  }

  //这个类实现的功能是，如果输入的文件名当前目录不存在，则输出提示信息
  private class MyChooser extends JFileChooser {
    private static final long serialVersionUID = 1L;

    MyChooser(String path) {
      super(path);
    }

    public void approveSelection() {
      File file = new File(getSelectedFile().getPath());
      if (file.exists())
        super.approveSelection();
      else JOptionPane.showMessageDialog(null, "你选择的文件不存在，请重新选择！");
    }
  }
}

